package servlet;

import dao.OrderDAO;
import pojo.Order;
import utils.ApiResult;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.List;

@WebServlet("/orders")
public class OrderServlet extends BaseServlet {

    // 查询所有订单
    public void findAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            List<Order> orders = OrderDAO.getAllOrders();
            sendJsonResponse(resp, new ApiResult(200, "查询所有订单成功", orders));
        } catch (SQLException e) {
            sendJsonResponse(resp, new ApiResult(500, "查询所有订单失败", e.getMessage()));
        }
    }

    // 新增订单
    public void placeOrder(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String buyer = req.getParameter("buyer");
        int bookId = Integer.parseInt(req.getParameter("bookId"));
        String bookName = req.getParameter("bookName");
        int quantity = Integer.parseInt(req.getParameter("quantity"));

        Order order = new Order();
        order.setUserId(buyer);
        order.setBookId(bookId);
        order.setBookName(bookName);
        order.setQuantity(quantity);
        order.setOrderDate(LocalDateTime.now());

        try {
            OrderDAO.placeOrder(order);
            sendJsonResponse(resp, new ApiResult(200, "新增订单成功", null));
        } catch (SQLException e) {
            sendJsonResponse(resp, new ApiResult(500, "新增订单失败", e.getMessage()));
        }
    }
    
    // 其他功能：更新订单、删除订单等方法可以根据需要进行实现
}
